package cn.com.swu.mianyangapp.ui.home;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import cn.com.swu.mianyangapp.databinding.FragmentHomeBinding;
import cn.com.swu.mianyangapp.net.NetRepository;
import cn.com.swu.mianyangapp.net.NetService;
import cn.com.swu.mianyangapp.result.BaseResult;
import cn.com.swu.mianyangapp.result.LoginResult;
import cn.com.swu.mianyangapp.result.UserInfo;
import cn.com.swu.mianyangapp.result.UserType;
import com.google.gson.Gson;
import okhttp3.Headers;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.w3c.dom.Text;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

public class HomeFragment extends Fragment {

    final String TAG1 = "home_login";
    final String TAG2 = "home_user_info";
    private FragmentHomeBinding binding;
    private String username;
    private String password;
    private ConstraintLayout conLogin;
    private ConstraintLayout conInfo;

    // userinfo con
    private TextView homeTextUsername;
    private TextView homeTextPhone;
    private TextView homeTextEmail;
    private TextView homeTextSex;
    private TextView homeTextAddress;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        conLogin = binding.homeConLogin;
        conInfo = binding.homeConInfo;
//        homeTextAddress = binding.
        homeTextUsername = binding.infoTextUsername;
        homeTextEmail = binding.infoTextEmail;
        homeTextPhone = binding.infoTextPhone;
        setUserInfo();

        if (UserInfo.SESSION != null && UserInfo.STATUS == 0) {
            conLogin.setVisibility(View.GONE);
            conInfo.setVisibility(View.VISIBLE);
        } else {
            conInfo.setVisibility(View.GONE);
            conLogin.setVisibility(View.VISIBLE);
        }

        EditText editTextUsername = binding.homeInputUsername;
        editTextUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                username = editable.toString();
                Log.v(TAG1, username);
            }
        });
        EditText editTextPassword = binding.homeInputPassword;
        editTextPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                password = editable.toString();
                Log.v(TAG2, password);
            }
        });

        Button buttonLogin = binding.homeButtonLogin;
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, String> map = new HashMap<>();
                map.put("username", username);
                map.put("password", password);

                NetRepository netRepository = new NetRepository();
                Call<ResponseBody> call = null;
                try {
                    call = netRepository.postStringFromFormDataCall("user/login", map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        String res = null;
                        try {
                            res = response.body().string();
                            Headers headers = response.headers();
                            UserInfo.SESSION = headers.get("Set-Cookie").split(";")[0];
                            Log.v(TAG1, UserInfo.SESSION);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        Gson gson = new Gson();
                        LoginResult loginResult = gson.fromJson(res, LoginResult.class);
                        Log.v(TAG1, res);

                        if (loginResult.status_code == 0){
                            UserInfo.STATUS = 0;
                            UserInfo.USERID = loginResult.userId;
                            UserInfo.ADDRESS = loginResult.address;
                            UserInfo.EMAIL = loginResult.email;
                            UserInfo.PHONE = loginResult.phone;
                            UserInfo.USERNAME = loginResult.username;
                            UserInfo.SEX = loginResult.sex;
                            conLogin.setVisibility(View.GONE);
                            conInfo.setVisibility(View.VISIBLE);
                        } else {
                            Toast.makeText(getActivity(), "登录出错", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.v(TAG1, "login error");
                    }
                });
            }
        });

        Button buttonRegister = binding.homeButtonRegister;
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, String> map = new HashMap<>();
                map.put("username", username);
                map.put("password", password);

                NetRepository netRepository = new NetRepository();
                Call<ResponseBody> call = null;
                try {
                    call = netRepository.postStringFromFormDataCall("user/register", map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        String res;
                        try {
                            res = response.body().string();
                            Headers headers = response.headers();
                            UserInfo.SESSION = headers.get("Set-Cookie").split(";")[0];
                            Log.v(TAG1, UserInfo.SESSION);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        Gson gson = new Gson();
                        LoginResult loginResult = gson.fromJson(res, LoginResult.class);
                        Log.v(TAG1, res);

                        if (loginResult.status_code == 0){
                            UserInfo.STATUS = 0;
                            UserInfo.USERID = loginResult.userId;
                            UserInfo.ADDRESS = loginResult.address;
                            UserInfo.EMAIL = loginResult.email;
                            UserInfo.PHONE = loginResult.phone;
                            UserInfo.USERNAME = loginResult.username;
                            UserInfo.SEX = loginResult.sex;
                            setUserInfo();
                            conLogin.setVisibility(View.GONE);
                            conInfo.setVisibility(View.VISIBLE);
                        } else {
                            Toast.makeText(getActivity(), "注册出错", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.v(TAG1, "register error");
                    }
                });
            }
        });

        return root;
    }

    private void setUserInfo() {
        homeTextUsername.setText(UserInfo.USERNAME);
        homeTextPhone.setText(UserInfo.PHONE);
        homeTextEmail.setText(UserInfo.EMAIL);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}